package com.ybkj.daijia.server.event.listener;

import com.ybkj.daijia.PushData;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.gexin.GeTuiMember;
import com.ybkj.daijia.server.event.model.OrderRushEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.OrderGroup;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderGroupService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.SmsTempletService;
import com.ybkj.daijia.server.websocket.WebSocketSend;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class OrderRushEventListener implements ApplicationListener<OrderRushEvent> {

    private static final Logger logger = LoggerFactory.getLogger(OrderRushEventListener.class);


    @Autowired
    private SmsTempletService smsTempletService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private DriverService driverService;

    @Autowired
    private OrderGroupService orderGroupService;

    @Autowired
    private SettingUtils settingUtils;


    @Autowired
    private CompanyService companyService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberAccountService memberAccountService;


    @Override
    @Async
    public void onApplicationEvent(OrderRushEvent event) {

        Order order = (Order) event.getSource();
        logger.debug("order Rush event:{}", order.getOrderNumber());

        Driver driver = driverService.findOne(order.getDriverId());

        //推送数据到浏览器
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderID", order.getId());
        jsonObject.put("driverID", driver.getId());
        jsonObject.put("type", "getrushorder");
        Company mainCompany = companyService.getMain();
        Company orderCompany = companyService.findOne(order.getCompanyId());
        WebSocketSend.boardcastToArea(jsonObject, orderCompany.getCityName(), mainCompany.getId());

        Long orderGroupId = order.getOrderGroupId();
        Long jiedanDriverId = null;
        if (null != orderGroupId) {
            OrderGroup orderGroup = orderGroupService.findOne(orderGroupId);
            if (null != orderGroup) {
                jiedanDriverId = orderGroup.getDriverId();
            }
        }

        //发送短信
        if (settingUtils.get().isSmsMainCompany()) {
            orderCompany = mainCompany;
        }
        SmsTemplet templet = smsService.findByAlias(orderCompany.getId(), SmsType.driverAccept);

        if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
            if (null == orderGroupId || (null != jiedanDriverId && jiedanDriverId
                .equals(driver.getId()))) {
                try {
                    //smsService.sendSms(order.getClientPhone(), "driverAccept", "{\"服务人员名\":\""+driver.getName()+"\",\"服务人员工号\":\""+driver.getUsername()+"\",\"服务人员电话\":\""+driver.getPhone()+"\",\"订单号\":\""+"***"+order.getOrderNumber().substring(8)+"\"}", orderCompany.getId(), 0, orderCompany.getSignName());
                    //发送短信（改）
                    com.alibaba.fastjson.JSONObject smsParam = new com.alibaba.fastjson.JSONObject();
                    smsParam.put("name", driver.getName());
                    smsParam.put("user", driver.getUsername());
                    smsParam.put("tel", driver.getPhone());
                    smsParam.put("order", order.getOrderNumber().substring(8));
                    smsService.sendSms(order.getClientPhone(), templet.getTemplateId(),
                        smsParam.toJSONString(), orderCompany.getId(), 0,
                        orderCompany.getSignName());
                } catch (Exception e) {
                    logger.error("发送短信发生异常：{}", e.getMessage());
                }
            }
        }

        Passenger passenger = memberService.findOnePassengerByPhone(order.getClientPhone());
        //给客户推送
        passenger.setCid(memberService.findCid(passenger.getId()));
        if (StringUtils.isNotBlank(passenger.getCid())) {

            if (null == orderGroupId || (null != jiedanDriverId && jiedanDriverId
                .equals(driver.getId()))) {
                try {
                    //发送设备推送
                    PushData pushData = new PushData();
                    pushData.setType("ORDER_ACCEPT");
                    pushData.setTitle("新提醒");
                    pushData.setDescription("服务人员已接受您的订单");
                    pushData.setData(order.getId());

                    GeTuiMember.push(passenger, pushData, settingUtils.get());
                } catch (IOException e) {
                    logger.debug("push error : " + e.getMessage());
                }
            }

        }

    }


}
